/**
 * 
 */
package es.cloudcast.server.persistence.dao.jdo;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import es.cloudcast.server.model.BasicModel;
import es.cloudcast.server.persistence.PersistenceException;
import es.cloudcast.server.persistence.dao.BasicQueryDAO;
import es.cloudcast.server.persistence.jdo.action.ActionProcessor;
import es.cloudcast.server.persistence.jdo.action.basic.CountAction;
import es.cloudcast.server.persistence.jdo.action.basic.ExistsAction;
import es.cloudcast.server.persistence.jdo.action.basic.GetAllAction;
import es.cloudcast.server.persistence.jdo.action.basic.GetObjectAction;

/**
 * Implementation for {@link BasicQueryDAO} for JDO
 * 
 * @see BasicQueryDAO
 * @author Samuel García Martínez <in0de> 
 *
 */
public class BasicJDOQueryDAO
	<T extends BasicModel, PK extends Serializable> 
					implements BasicQueryDAO<T, PK> {
	
	protected PersistenceManagerFactory PMF;	
	protected Class<T> persistentClass;	
		
	@SuppressWarnings("unchecked")
	public BasicJDOQueryDAO(PersistenceManagerFactory PMF) {
		this.PMF = PMF;
		persistentClass = (Class<T>) ((ParameterizedType) getClass()
                	.getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	public Integer count() throws PersistenceException {
		return (Integer) ActionProcessor.process(new CountAction(persistentClass), PMF);
	}
	
	public Boolean exists(PK id) throws PersistenceException {
		return (Boolean) ActionProcessor.process(new ExistsAction(id, persistentClass), PMF);
	}

	@SuppressWarnings("unchecked")
	public T get(PK id) throws PersistenceException {
		return (T) ActionProcessor.process(new GetObjectAction(id, persistentClass), PMF);
	}

	@SuppressWarnings("unchecked")
	public List<T> getAll() throws PersistenceException {
		return (List<T>) ActionProcessor.process(new GetAllAction(persistentClass), PMF);
	}

}
